﻿using UnityEngine;
using System.Collections;

public class HudBase : MonoBehaviour
{
    protected Vector3 _deltaPos = new Vector3(0, 2.5f, 0);
    private Transform _myTransform;
    private bool _bUpdate = false;
    private SpawnPool _pool;
    private float tempTime = 0.0f;
    
    public float spwanTime = 0.8f;
    private bool bAutoPool = false;
    private bool bAlwaysShow = false;
    private Transform followNode = null;
    Vector3 v = Vector3.zero;
    private Camera uiCamera;

    void OnEnable()
    {
        _bUpdate = true;
        _myTransform = transform;
        tempTime = 0.0f;
    }

    void Awake()
    {
        Init();
    }

    protected virtual void Init() { }

    void Start()
    {
        PoolManager.Pools.TryGetValue(GlobleConfig.ResPath.UIPool, out _pool);
        uiCamera = GameObject.FindGameObjectWithTag(GlobleConfig.ResPath.UICamera).GetComponent<Camera>();
    }


    void OnDisable()
    {
        _bUpdate = false;
        _pool = null;
    }

    private void _Dispose()
    {
        if (bAutoPool)
        {
            if (_pool)
            {
                _pool.Despawn(_myTransform);
            }
        }
        else
        {
            DestroyObject(gameObject);
        }
    }

    protected void Update()
    {
        if (!bAlwaysShow)
        {
            if (tempTime < spwanTime)
            {
                tempTime += Time.deltaTime;
            }
            else
            {
                _bUpdate = false;
                _Dispose();
            }
        }
    }

    void LateUpdate()
    {
        if (_bUpdate)
        {
            _UpdatePos();
        }
    }

    private void _UpdatePos()
    {
        if (followNode != null && Camera.main != null)
        {
            v = Camera.main.WorldToScreenPoint(followNode.position + _deltaPos);
            v = uiCamera.ScreenToWorldPoint(v);

            v.z = 0.0f;
            _myTransform.position = v;
            v = _myTransform.localPosition;
            v.z = 0;
            _myTransform.localPosition = v;
        }
        else
        {
            _Dispose();
        }
    }


    public void SetHud(Transform node, bool autoPool = true, bool alwayShow = false)
    {
        GameObject uiRoot = GameObject.FindGameObjectWithTag("UIRoot");

        if (uiRoot)
        {
            Transform root = uiRoot.transform;
            root = CHelper.FindNode(root, "3D");
            CHelper.Attach(root, transform);
        }
        else
        {
            GameObject ca = GameObject.FindGameObjectWithTag("GUI Camera");
            CHelper.Attach(ca.transform, transform);
        }

        NGUITools.MarkParentAsChanged(gameObject);
        followNode  = node;
        _bUpdate    = true;
        bAlwaysShow = alwayShow;
        bAutoPool   = autoPool;
    }

    public void SetDeltaPos(Vector3 vec)
    {
        _deltaPos += vec;
    }

}
